const user = {
  namespaced: true, // 开启命名空间，调用时需指定模块名
  state: {
    userInfo: {},
    userId: "",
    username: "",
    token: null,
    refreshToken: null,
    phone: "",
    wechatName: "",
    wechatOpenId: "",
    wechatUnionId: "",
    headImage: "",
    isLogin: false,
  },
  mutations: {
    // 修改token
    setToken(state, token) {
      state.token = token;
    },
    
    // 设置刷新token
    setRefreshToken(state, refreshToken) {
      state.refreshToken = refreshToken;
    },
    
    // 设置登录状态
    setLoginStatus(state, status) {
      state.isLogin = status;
    },
    
    // 修改用户信息
    setUserInfo(state, info) {
      console.log('修改用户信息', state, info);
      // 1. 先保存原始的用户信息到 state.userInfo 对象
      state.userInfo = {
        // userId: info.userId || info.buyerUserId || "",
        // username: info.username || info.name || info.wechatName || "",
        // phone: info.phone || "",
        // wechatName: info.wechatName || "",
        // wechatOpenId: info.wechatOpenId || "",
        // wechatUnionId: info.wechatUnionId || "",
        // headImage: info.headImage || "",
        // 复制所有其他用户信息
        ...info
      };
      // // 2. 同时更新各个独立的字段（保持向后兼容）
      // state.userId = info.userId || info.buyerUserId || "";
      // state.username = info.username || info.name || info.wechatName || "";
      // state.phone = info.phone || "";
      // state.wechatName = info.wechatName || "";
      // state.wechatOpenId = info.wechatOpenId || "";
      // state.wechatUnionId = info.wechatUnionId || "";
      // state.headImage = info.headImage || "";
      // state.isLogin = true;
      
      // // 存储其他需要的用户信息
      // Object.keys(info).forEach(key => {
      //   if (!(key in state)) {
      //     state[key] = info[key];
      //   }
      // });
    },
    
    // 清除用户信息（登出）
    clearUserInfo(state) {
      state.userInfo = {};
      state.userId = "";
      state.username = "";
      state.token = null;
      state.refreshToken = null;
      state.phone = "";
      state.wechatName = "";
      state.wechatOpenId = "";
      state.wechatUnionId = "";
      state.headImage = "";
      state.isLogin = false;
    }
  },
  actions: {
    // 异步登录
    login({ commit }, userData) {
      return new Promise((resolve, reject) => {
        commit("setToken", userData.token);
        commit("setRefreshToken", userData.refreshToken);
        commit("setUserInfo", userData);
        
        // 存储完整用户信息到localStorage以便持久化
        if (userData.token) {
          localStorage.setItem('token', userData.token);
          localStorage.setItem('refreshToken', userData.refreshToken || '');
          // 存储完整的用户信息对象
          localStorage.setItem('userInfo', JSON.stringify(userData));
        }
        
        resolve(true);
      });
    },
    
    // 登出操作
    logout({ commit }) {
      commit("clearUserInfo");
      localStorage.removeItem('token');
      localStorage.removeItem('refreshToken');
      localStorage.removeItem('userInfo');
    },
    
    // 从localStorage恢复登录状态
    restoreLoginState({ commit }) {
      const token = localStorage.getItem('token');
      const refreshToken = localStorage.getItem('refreshToken');
      const userInfoStr = localStorage.getItem('userInfo');
      
      if (token) {
        commit("setToken", token);
        commit("setRefreshToken", refreshToken);
        commit("setLoginStatus", true);
        
        if (userInfoStr) {
          try {
            const userInfo = JSON.parse(userInfoStr);
            commit("setUserInfo", userInfo);
          } catch (e) {
            console.error('解析用户信息失败:', e);
          }
        }
      }
    }
  },
  getters: {
    // 计算是否登录
    isLogin(state) {
      return !!state.token;
    },
    
    // 获取完整用户信息
    userInfo(state) {
      console.log(state);
      return state.userInfo;
    }
  },
};

export default user;
